package mypackage.dao.impl;

import mypackage.bean.*;
import mypackage.dao.GoodOrderDao;
import mypackage.dao.HistoryOrderDao;
import mypackage.dao.ProfitsDao;
import mypackage.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author YH925
 * @create 2021/12/10 8:26
 */
public class HistoryOrderDaoImpl implements HistoryOrderDao {
    private final ProfitsDao profitsDao = new ProfitsDaoImpl();
    Connection connection = null;

    {
        try {
            connection = JDBCUtils.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    QueryRunner runner = new QueryRunner();

    /**
     * 购买一件商品
     * @param goodsId
     * @param clientId
     * @param amount
     * @param price
     * @param addressId
     */
    @Override
    public void insertOneData(String  goodsId,int clientId,int amount,double price,int addressId) {

        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        String sql = "insert into historyOrders values(?,?,?,?,?,?,to_date(?,'YYYY-MM-DD HH24:MI:SS'),?)";


        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm;ss");
        String time = dateFormat.format(date);

        try {
            runner.update(connection,sql,null,goodsId,clientId,
                    amount,price,"小米之家",time,addressId);
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    @Override
    public Boolean findOrderByClient(String goodsId, int clientId) {
        String sql = "select * from historyOrders where goodsId = ? and clientId = ?";
        BeanHandler<HistoryOrders>handler = new BeanHandler<>(HistoryOrders.class);
        HistoryOrders query = null;
        try {
            query = runner.query(connection, sql, handler, goodsId, clientId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (query != null){
            return true;
        }
        return false;
    }

    /**
     * 将某人的购物车清空
     * @param clientId 传入当前用户的id
     */
    @Override
    public void insertDataFromChart(int clientId,int addressId) {
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        GoodOrderDao dao = new GoodOrderDaoImpl();
        List<GoodOrder> orderList = dao.findGoodChartWithGood(clientId);
        for (GoodOrder goodOrder : orderList) {
            insertOneData(goodOrder.getGoodId(),clientId,goodOrder.getAmount(),goodOrder.getPrice(),addressId);
            if(profitsDao.isExist(goodOrder.getGoodId())){

                //存在，更新

                GoodsImpl goods = new GoodsImpl();
                Goods goods1 = goods.selectGoodsById(goodOrder.getGoodId());
                double inputMoney = goods1.getInputMoney();
                double profits = goodOrder.getPrice() - goods1.getInputMoney();

                profitsDao.update(goodOrder.getGoodId(), goodOrder.getAmount(), profits,inputMoney,goodOrder.getPrice());
            }else {
                //不存在，插入
                GoodsImpl goods = new GoodsImpl();
                Goods goods1 = goods.selectGoodsById(goodOrder.getGoodId());
                double inputMoney = goods1.getInputMoney();
                double profit = goodOrder.getPrice() - inputMoney;
                profitsDao.insert(goodOrder.getGoodId(),goodOrder.getPrice(),inputMoney*goodOrder.getAmount(),profit,goodOrder.getAmount());
            }
        }
    }

    /**
     * 查看消费过多少件商品
     * @param clientId
     * @return
     */
    @Override
    public int findConsumeAmount(int clientId) {
        String sql = "select count(*) from HISTORYORDERS where CLIENTID = ?";
        ScalarHandler<Object> handler = new ScalarHandler<>();
        Object obj = null;
        try {
            obj = runner.query(connection, sql, handler, clientId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        Integer count;
        if (obj == null){
            count  = 0;
        }

        count = Integer.parseInt(obj.toString());
        return count;
    }

    /**
     * 查看共消费过多少钱
     * @param clientId
     * @return
     */
    @Override
    public double findConsumeMoney(int clientId) {
        String sql = "select sum(price) from HISTORYORDERS where CLIENTID = ?";
        ScalarHandler<Object>handler = new ScalarHandler<>();
        Object obj = null;
        try {
            obj = runner.query(connection, sql, handler, clientId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        double price;
        if (obj==null){
            price =  0;
        }else price = Double.parseDouble(obj.toString());

        return price;
    }

    @Override
    public List<ReceiveOrder> findAllConsumeRecord(int clientId) {
        String sql = "select h.id,g.NAME,h.AMOUNT,h.PRICE,h.SENDADDRESS,h.SALETIME,a.ACCEPTADDRESS,a.ACCEPTNAME,a.TEL\n" +
                "from HISTORYORDERS h,address a,goods g \n" +
                "where h.ADDRESSID = a.ID and h.GOODSID = g.ID and a.CLIENTID = ?";
        BeanListHandler<ReceiveOrder> handler = new BeanListHandler<>(ReceiveOrder.class);
        List<ReceiveOrder> historyOrders = null;
        try {
            historyOrders = runner.query(connection, sql, handler, clientId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return historyOrders;
    }
}
